var express = require('express');
var router = express.Router();
var identityKey = 'skey';

const Util = require('../note/Util');
const db = require('../note/db');
router.get('/', function(req, res) {
   res.render('add', { title: 'note', data:{msg:'hello node!',content:'我只想说一句MMP',uname:'suoge'} });
});

router.post('/',function(req,res){
  var data = req.body;
  var id = data['id'];
  var uid = req.session.loginUserId;
  var title = data['title'];
  var content = data ['content'];
  var desc = data ['descs'].substr(0,100);
  var uptime =parseInt(new Date().getTime()/1000) ;

  if(id){
    // 更新
    try {
      db.notes.find({
        where:{
          id:id
        }
      }).then(ret=>{
        ret.title = title;
        ret.descs = desc;
        ret.uptime = Date.parse(new Date())/1000;
        ret.save().then(ret=>{
          db.contents.find({
            where:{
              nid:id
            }
          }).then(ret=>{
            ret.contents = content;
            ret.save().then(ret=>{
              res.json({ret_code: 0, ret_msg: '笔记更新成功'});
            }).catch(e=>{
              console.log(e);
              res.json({ret_code: 1, ret_msg: '笔记更新失败_2'});});
          })
        }).catch(e=>{
          console.log(e);
          res.json({ret_code: 1, ret_msg: '笔记更新失败_1'});
        })
      })
    } catch (e) {
      console.log(e);
      res.json({ret_code: 1, ret_msg: '笔记更新失败'});
    }
  }else{
    // 新增
    try {
      db.notes.create({
        uid:uid,
        title:title,
        descs:desc,
        uptime:uptime
      }).then(ret=>{
        // 主表新增成功
          // console.log(ret,'主表保存结果',ret.id);
          var nid = ret.id;
          try {
            db.contents.create({
              nid:nid,
              contents:content
            }).then(ret=>{
              res.json({ret_code: 0, ret_msg: '笔记新建成功',datas:data});
            }).catch(e=>{
              res.json({ret_code: 1, ret_msg: '笔记新建失败_2'});
            })
          } catch (e) {
            res.json({ret_code: 1, ret_msg: '笔记新建失败_1'});
          }
      })
    } catch (e) {
      console.log(e);
      res.json({ret_code: 1, ret_msg: '网络错误'});
    }
  }

});

module.exports = router;
